import socket
import selectors

POLLIN = selectors.EVENT_READ       # 1
POLLOUT = selectors.EVENT_WRITE     # 2

class Poller:
    def __init__(self):
        self.selector = selectors.DefaultSelector()

    def close(self):
        self.selector.close()

    def register(self, sock, mask, callback=None):
        """ 这里注意params匹配关系 """
        self.selector.register(fileobj=sock, events=mask, data=callback)

    def unregister(self, sock):
        self.selector.unregister(sock)

    # def poll(self):
    #     events = self.selector.select()
    #     for key, mask in events:
    #         callback = key.data
    #         sock = key.fileobj
    #         callback(sock, mask)

    def poll(self):
        """ 模拟 zmq.Poller.poll() 的返回值 """
        events = self.selector.select()
        list_= [(key.fileobj, mask) for key, mask in events]
        # callback = key.data
        return list_



# class HerosysBaseSocket:
#     """ 模拟TCP的接口 """
#     def __init__(self):
#         self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#     def __del__(self):
#         self.sock.close()


# class HerosysServer(HerosysBaseSocket):
#     def __init__(self, ipaddr):
#         super().__init__()
#         self.sock.bind(ipaddr)

#     def sendto(self, msg, target):
#         bytes_msg = dict2json(msg)
#         self.sock.sendto(bytes_msg, target)

#     def recvfrom(self):
#         bytes_msg, addr = self.sock.recvfrom(BUFFER_SIZE)
#         dict_msg = json2dict(bytes_msg)
#         return dict_msg, addr


# class HerosysClient(HerosysBaseSocket):
#     def __init__(self, server_ipaddr):
#         super().__init__()
#         self.sock.connect(server_ipaddr)

#     def send(self, msg: dict):
#         bytes_msg = dict2json(msg)
#         self.sock.send(bytes_msg)

#     def recv(self):
#         bytes_msg = self.sock.recv(BUFFER_SIZE)
#         dict_msg = json2dict(bytes_msg)
#         return dict_msg
